import EventEmitter from "events"
import type { TextModel } from "./textModel"

export interface Selection {
  anchor: number
  focus: number
}

export class SelectionModel extends EventEmitter {
  // @ts-ignore
  private textModel_?: TextModel
  public selection: Selection = { anchor: 0, focus: 0 }
  constructor(textModel: TextModel) {
    super()
    this.textModel_ = textModel
  }

  getSelection() {
    return { ...this.selection }
  }

  setSelection(selection: Selection) {
    if (
      selection &&
      this.selection &&
      selection.anchor === this.selection.anchor &&
      selection.focus === this.selection.focus
    ) {
      return
    }
    this.selection = { ...selection }
  }

  isCollapsed() {
    return this.selection && this.selection.anchor === this.selection.focus
  }

  isBackward() {
    return this.selection && this.selection.anchor > this.selection.focus
  }

  isEnd() {
    return !this.textModel_
      ?.getSpacers()
      [this.selection.anchor + 1]?.replace(/\s\S/, "")
  }
}
export default SelectionModel
